<template>
  <div class="document-create-title">
    <el-form label-position="top" :model="params" :rules="rules" ref="ruleForm">

      <el-form-item :label="`${$t('wiki.create.textTitle.label1')}：`" class="create-item item-title" prop='permission'>
        <el-input class="title" v-model="params.title" :placeholder="$t('common.placeholder.inputSomething', {data1:$t('wiki.create.textTitle.label1')})"></el-input>
      </el-form-item>
      <p class="title-error" v-if="params.title && params.title.length > 100">{{$t('wiki.create.textTitle.tips1')}}</p>
      <p class="title-error" v-if="msg && !params.title">{{$t('wiki.create.textTitle.msg1')}}</p>

      <el-form-item :label="`${$t('wiki.create.textTitle.label2')}：`" class="create-item" prop="typeId">
        <!-- <base-cascader
          ref="listTypeCascader"
          style="width: 188px"
          :options="params.options"
          check-strictly
          filterable
          v-model="params.typeId">
        </base-cascader> -->
        <treeselect
          class="typeSelect"
          :clearable="true"
          :searchable="true"
          :open-on-click="true"
          :placeholder="$t('common.placeholder.inputSomething', {data1:$t('wiki.create.textTitle.label2')})"
          :alwaysOpen="false"
          :options="params.options"
          v-model="params.typeId"
          :noOptionsText="$t('common.base.tip.noData')"
          :noResultsText="$t('common.base.tip.noData')"
          :normalizer="normalizer"
          :style="{'--transform': transform}"
          @open="reverseOpen"
          @close="reverseClose"
        />
      </el-form-item>

      <el-form-item :label="`${$t('wiki.create.textTitle.label3')}：`" class="create-item permission-item" prop="permission">
        <el-radio-group v-model="params.permission">
          <el-radio :label="0">
            {{$t('common.base.inside')}}
          </el-radio>
          <el-tooltip :content="$t('wiki.create.textTitle.tips3')" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-radio :label="1" >
            {{$t('common.base.outside')}}
          </el-radio>
          <el-tooltip :content="$t('wiki.create.textTitle.tips4')" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
<!--          <el-tooltip content="当前未开启外部分享设置，请到PC端系统设置-知识库设置中启用" placement="top" v-else>
            <i class="el-icon-question"></i>
          </el-tooltip>-->
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="`${$t('wiki.create.textTitle.label4')}：`" class="create-item" prop="role" v-if="params.permission === 0">
          <!-- :inputDisabled="isDisabled" -->
        <!-- <biz-form-remote-select
          :class="`wiki-role-select`"
          v-model="params.role"
          placeholder='请选择授权角色'
          :remoteMethod="fetchRoles">
          <template slot="option" slot-scope="{option}">
            <div :key="option.id">
              {{option.name}}
            </div>
          </template>
        </biz-form-remote-select> -->
        
        <!-- <el-select
          v-model="params.role"
          multiple
          filterable
          collapse-tags
          class="wiki-role-select"
          :placeholder="$t('common.placeholder.inputSomething', {data1:$t('common.base.authRole')})">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.text"
            :value="item.id">
          </el-option>
        </el-select> -->
        
        <biz-role-select
          v-model="params.role"
          multiple
          filterable
          collapse-tags
          class="wiki-role-select"
          :placeholder="$t('common.placeholder.inputSomething', { data1: $t('common.base.authRole') })"
        >
        </biz-role-select>

      </el-form-item>

      <el-form-item :label="`${$t('wiki.create.textTitle.label5')}：`" class="create-item" prop="isOpenComment" v-if="params.permission === 1">
        <el-radio-group v-model="params.isOpenComment">
          <el-radio :label="1">
            {{$t('common.base.yes')}}
          </el-radio>
          <el-radio :label="2">
            {{$t('common.base.no')}}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="`${$t('wiki.create.textTitle.label6')}：`" class="create-item label-item">
        <el-tag class="search-tag" closable @close="handleTags(tag)" v-for="(tag,index) in params.label" :key="index">{{tag}}</el-tag>
        <el-input v-if="inputVisible" class="input-new-tag" @keyup.enter.native="addTags" @blur="addTags" v-model="tagValue" ref="saveTagInput"></el-input>
        <div class="icon-add-tags-btn" @click="showInput" v-if="!params.label || (params.label.length < 4)">
          <i class="iconfont icon-add2 icon-addTags"></i><span>{{$t('wiki.create.textTitle.btn1')}}</span>
        </div>
        <!-- <el-button
          plain
          class="icon-add-tags-btn"
          @click="showInput"
          v-if="!params.label || (!inputVisible && params.label.length < 4)">addTags
          <i class="iconfont icon-add2 icon-addTags"></i><span>添加标签</span>
        </el-button> -->
      </el-form-item>
      <p class="title-error" v-if="tagValue && tagValue.length > 10">{{$t('wiki.create.textTitle.tips5')}}</p>

      <el-form-item :label="`${$t('wiki.create.textTitle.label7')}：`" class="create-item">
        <div class="file">
          <div class="base-comment-attachment base-file__preview file-item file-item-ul" v-if="params.form.attachments && params.form.attachments.length > 0">
            <base-file-item v-for="file in params.form.attachments" :Source="params.form.attachments" :key="file.id" :file="file" @delete="deleteFile" size="small"></base-file-item>
          </div>
          <button type="button" class="base-comment-tool file-button" @click="chooseFile">
            <i class="iconfont icon-attachment"></i> {{$t('wiki.create.textTitle.btn2')}}
          </button> 
          <input type="file" ref="input" @change="handleChange" multiple>
          <div class="base-comment-cover loading" v-if="!allowOperate">
            <base-spin :text="$t('common.base.waiting')"></base-spin>
          </div>
        </div> 
      </el-form-item>
       <!-- 故障库 Start -->
      <template v-if="isFault">
        <!-- 适用产品类型 -->
        <el-form-item :label="`${$t('wiki.create.textTitle.label8')}：`" prop="productTypeList" class="create-item">
          <div class="file">
          <Cascader
            :value="CloneValue"
            collapse-tags
            :options="CloneData"
            :props="{
                multiple: true,
                label:'name',
                value:'id',
                children:'tasks'
              }"
            clearable
            @change="CascaderChange"
            >
            </Cascader>
          </div> 
        </el-form-item>
         <!-- 故障现象 -->
        <el-form-item :label="`${$t('wiki.create.textTitle.label9')}：`" prop="faultPerformance" class="create-item">
          <div class="file">
            <el-input type="textarea" :placeholder="$t('common.placeholder.inputSomething', {data1:$t('wiki.create.textTitle.label9')})" v-model="params.faultPerformance" style="width:240px;"  :maxlength="100" />
          </div> 
        </el-form-item>
         <!-- 故障原因 -->
        <el-form-item :label="`${$t('wiki.create.textTitle.label10')}：`" prop="faultReason" class="create-item">
          <div class="file">
            <el-input  type="textarea" :placeholder="$t('common.placeholder.inputSomething', {data1:$t('wiki.create.textTitle.label10')})" v-model="params.faultReason" style="width:240px;"  :maxlength="100" />
          </div> 
        </el-form-item>
        <!-- 维修预估费用(元) -->
        <el-form-item :label="`${$t('wiki.create.textTitle.label11')}：`" class="create-item">
          <div class="file">
            <PriceRange :key="`PriceRange_${key}`"  :value="[params.repairCostBegin,params.repairCostEnd]"  @update="PriceRangeUpdate" style="width:250px;"/>
          </div> 
        </el-form-item>
      </template>
       <!-- 故障库 End -->

    </el-form>
  </div>
</template>

<script>
import platform from '@src/platform';
import Uploader from '@src/util/uploader';
import { getRoleList } from '@src/api/Repository'
import { cloneData } from '@src/api/ProductV2Api'

import Treeselect from '@riophae/vue-treeselect'
import PriceRange from './PriceRange'
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import {Cascader } from 'element-ui';
import i18n from '@src/locales'
export default {
  components: {
    Treeselect,
    PriceRange,
    Cascader

  },
  name: 'text-title',
  props: {
    value: {
      type: Object,
      default: () => ({})
      },
    isFault:{
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      params: this.value,
      inputVisible: false, // 添加标签input显示标识
      tagValue: '', // 添加的标签
      options: [], // 文章分类
      pending: false,
      msg: '',
      rules: {
        title: [
          { required: true, message: i18n.t('wiki.create.textTitle.msg1'), trigger: 'blur' },
          { max: 100, message: i18n.t('wiki.create.textTitle.msg2'), trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: i18n.t('wiki.create.textTitle.msg3'), trigger: 'change' }
        ],
        permission: [
          { required: true, message: i18n.t('wiki.create.textTitle.msg4'), trigger: 'change' }
        ],
        productTypeList: [
          { required: true, message: i18n.t('wiki.create.textTitle.msg5'), trigger: 'change' },
          { validator: (rule, value, callback)=>{
             if(value.length>10){
              callback(i18n.t('wiki.create.textTitle.msg6'))
             }
            callback()
          }, trigger: 'change' }
        ],
        faultPerformance: [
          { required: true, message: i18n.t('wiki.create.textTitle.msg7'), trigger: 'change' }
        ],
        faultReason: [
          { required: true, message: i18n.t('wiki.create.textTitle.msg8'), trigger: 'change' }
        ],
      },

      roleList: [],
      transform: 'rotate(0deg)',
      CloneData:[],
      CloneValue:[],
      CloneDataMap:new Map(),
      key:0,
    }
  },
  watch:{
    params(){
      this.key = Date.now()
    }
  },
  computed: {
    // 加载显示
    allowOperate(){
      return !this.pending
    }
  },
  mounted () {
    this.getRoleList()
    this.GetCloneData()
  },
  methods: {
    PriceRangeUpdate({newValue}){
      this.$set(this.params, 'repairCostBegin',newValue[0]);
      this.$set(this.params, 'repairCostEnd',  newValue[1]);
    },
    GetCloneData(){
      cloneData()
      .then(res=>{
          if(res.code !== 0){
            this.$message.error(res.message)
            return
          }
          let {result} = res
          this.deleteEmpty(result);
          this.CloneData = result

          const DeepResult = (node,Parent=null)=>{
             node.Parent = Parent
             node.hierarchyName = Parent?[...Parent.hierarchyName,node.name]:[node.name]
             if(node.conData === 1){
                this.CloneDataMap.set(node.id,{...node})
             }
           
             if(node?.tasks?.length){
                for(let item of node.tasks){
                  DeepResult(item,node)
                }
             }
          }
          for(let item of result){
            DeepResult(item,null)
          }
          // 产品类型有数据就回填
          if(this.params?.productTypeList?.length){
             this.initialValue(this.params.productTypeList)
          }
      })
    },
    // 删除空子集
    deleteEmpty (list) {
      list.forEach(item => {
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    CascaderChange(value){
      let list = []
      if(value?.length){
        list = value.flat(Infinity).filter((value,index,arr)=>{
          return arr.findIndex(v=>v===value) === index
        })
      }
      this.params.productTypeList = list.map(i=>{
        let value = this.CloneDataMap.get(i)
        if(value){
        return{
          id:value.id,
          name:value.name,
          hierarchyName:value?.hierarchyName.join('/'),
        }
        }

      }).filter(item=>!!item)
    },
    initialValue(productTypeList,unwatch = null){
      const deep = (node,list)=>{
        list.unshift(node.id)
        if(node.Parent){
          deep(node.Parent,list)
        }
        return list
      }
        productTypeList.map(item=>{
          let find = this.CloneDataMap.get(item.id)
          let ids = []
          if(find){
           deep(find,ids)
           this.CloneValue.push(ids)
          }
        })
        unwatch && unwatch()
    },
    reverseClose() {
      this.transform = 'rotate(0deg)'
    },
    reverseOpen() {
      this.transform = 'rotate(180deg)'
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.subTypes?.length ? node.subTypes : void 0
      }
    },
    // /** 
    //  * @description 获取角色列表
    // */
    // fetchRoles(params) {
    //   return (
    //     getSettingRoleList(params).then((result = {}) => {
    //       result.list = result.list.map((role) =>
    //         Object.freeze({
    //           label: role.name || '',
    //           value: role.id || '',
    //           ...role
    //       }))
    //       return result
    //     })
    //   )
    // },
    getRoleList() {
      getRoleList().then(res => {
        res.succ && (this.roleList = res.data || [])
      }).catch(err => {
        console.log(err)
      })
    },
    // 点击加号显示标签输入框
    showInput () {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput?.$el.querySelector('input')?.focus()
      })
    },
    // 添加标签，最多5个
    addTags () {
      if(this.tagValue) {
        if(this.params.label.indexOf(this.tagValue) != -1) {
          this.$platform.notification({
            title: this.$t('wiki.create.textTitle.tips6'),
            type: 'error',
          });
        } else {
          if (this.tagValue.length <= 10) {
            this.params.label.push(this.tagValue);
          }
        }
      }
      this.inputVisible = false;
      this.tagValue = '';
    },
    // 删除标签
    handleTags (tag) {
      this.params.label.splice(this.params.label.indexOf(tag), 1);
    },
    // 文件存储form结构
    buildForm(){
      return {
        content: '',
        attachments: [],
        showInOwn: 0
      }
    },
    // 选择文件
    handleChange(event){
      const files = event.target.files;
      if(!files || !files.length) return;
      let form = this.params.form;

      if(form.attachments.length + files.length > Uploader.WIKI_FILE_MAX_NUM) {
        let message = this.$t('common.base.uploadModal.uploadCountTips', {count:Uploader.WIKI_FILE_MAX_NUM});
        let max = Uploader.WIKI_FILE_MAX_NUM - form.attachments.length;

        if(max > 0 && files.length > max){
          message +=  `, ${this.$t('common.base.uploadModal.canUploadCountTips',{count:max})}`;
        }

        return platform.alert(message)
      }

      this.pending = true;

      Uploader.batchUploadWithParse({files, action: '/files/upload/wiki', source: 'wiki'}).then(result => {
        let {success, error} = result;

        if(error.length > 0){
          let message = error.map(item => item.message).join('\n');
          //此处不能return
          platform.alert(message)
        }

        if(success.length > 0){
          form.attachments = form.attachments.concat(success);
        }
      })
        .catch(err => console.error(err))
        .then(() => this.pending = false)
    },
    // 触发inputclick事件选择文件
    chooseFile () {
      if(this.pending) return platform.alert(this.$t('common.base.uploadModal.tips1'));
      if(this.params.form.attachments.length >= Uploader.WIKI_FILE_MAX_NUM) {
        return platform.alert(this.$t('common.base.uploadModal.uploadCountTips', {count:Uploader.WIKI_FILE_MAX_NUM}));
      }

      this.$refs.input.value = null;
      this.$refs.input.click();
    },
    // 删除文件
    deleteFile(file) {
      let index = this.params.form.attachments.indexOf(file);
      if(index >= 0) {
        this.params.form.attachments.splice(index, 1);
      }
    },

    async titleCheck() {
      return await new Promise((resolve,reject)=>{
         this.msg = '';
         if(!this.params.title) {
           this.msg = this.$t('wiki.create.textTitle.msg1');
           resolve(false)
         }
         if(this.params.title.length > 100) {
          resolve(false)
         }
        this.$refs.ruleForm.validate((valid) => {
          if(valid){
            resolve(true)
           }else{
            resolve(false)
           }
         })
      }).then(res=>{
        return res
      })
    },
  }
}
</script>

<style lang="scss">
.document-create-title {
  background: #fff;

  .title-error {
    height: 17px;
    color: #f56c6c;
    font-size: 12px;
    line-height: 12px;
    margin: 0;
    padding-top: 5px;
  }

  .create-item {
    width: 100%;
    padding: 12px 0 20px 0;
    margin: 0;

    border-bottom: 1px solid #EBEBEB;

    .el-radio {
      line-height: 30px;

      .el-radio__label {
        font-size: 13px;
      }
    }

    .search-tag {
      border: 1px solid #D9D9D9;
      background: #fff;
      color: #262626;
      line-height: 32px;
      height: 32px;
      vertical-align: top;
      font-size: 14px;
      font-weight: 400;
      margin-right: 12px;
      i {
        color: #595959;
        font-size: 16px;
        &:hover {
          background: #fff;
        }
      }
    }

    .input-new-tag {
      display: inline-block;
      width: 140px;
      ::v-deep input:focus {
        border-color: $color-primary-light-6;
      }
    }

    .input-new-tag {
      vertical-align: middle;
    }
    .icon-add-tags-btn {
      // display: inline-block;
      position: relative;
      height: 32px;
      line-height: 32px;
      padding: 0 12px;
      border: 1px solid $color-primary-light-6;
      color: $color-primary-light-6;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      display: inline-flex;
      align-items: center;
      vertical-align: middle;
      margin-right: 12px;
      .icon-addTags {
        margin-right: 8px;
        // @include fontColor();
      }
    }
    
    
    input[type='file']{
      display: none !important;
    }

    .file {
      font-size: 0;
      // margin-left: 82px;

      .file-item-ul {
        .base-file-info{
            display: flex;
            justify-content: flex-start;
          .base-file-info-name {
            padding-top: 4px;
          }
        }
      }

      .file-button {
        vertical-align: middle;
        margin-left: 8px;
      }

      .loading {
        bottom: 10px;

        .base-spin-text {
          padding: 0;
        }
      }
    }

    .el-input__inner {
      border-color: #e0e1e2;
    }
    
  }

  .item-title {

    .el-form-item__content {

      input {
        border: none;
        width: calc(100% - 65px);
      }
    }

    .title {
      width: calc(100% - 65px);

      .el-input__inner {
        border: none;
      }
    }
  }
}

.document-type-cascader {
  .el-cascader-menu__item {
    display: flex;
    align-items: center;

    line-height: 21px;

    & > div {
      height: 21px;
      width: 100%;
      line-height: 21px;
      position: relative;
    }

  }
  .el-cascader-menu {
    max-height: 204px;
  }

  .el-cascader-menu__item--extensible {
    font-family: "iconfont" !important;

    &::after {
      content: "";
      right: 5px;
    }

    .iconfont {
      color: #bfcbd9;
      position: absolute;
      right: -10px;
      top: 0;
    }

  }
}

.wiki-role-select {
    width: 240px;
    display: inline-block;
    // margin-bottom: 10px;
}

</style>

<style lang="scss" scoped>
  .permission-item {
    ::v-deep .el-radio {
      margin-right: 0;
    }
    ::v-deep .el-radio-group {
      white-space: nowrap;
    }
    .el-icon-question {
      position: relative;
      top: 1px;

      font-size: 14px;
      color: #8C8C8C;
      margin: 0 60px 0 12px;
    }
  }

  ::v-deep .base-cascader {
    margin-bottom: 0;
  }
  .label-item {
    font-size: 0;
  }

  ::v-deep .typeSelect {
    width: 240px;

    .vue-treeselect__option--selected {
      background-color: #f5f5f5;
      border: 1px solid #e9e9eb;
    }
    .vue-treeselect__x-container:hover {
      color: #ccc;
    }
    .vue-treeselect__control-arrow-container:before {
      content: url("../../../../../assets/svg/downArrow.svg");
      position: absolute;
      top: 7px;
      right: 7px;
      transform: var(--transform) !important;
    }
    .vue-treeselect__control-arrow-container svg:first-child {
      display: none;
    }
  }

  .input-new-tag ::v-deep input:focus {
    border: 1px solid $color-primary-light-6;
  }
</style>